<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>案例-头像上传</title>
  <link rel="stylesheet" href="./lib/bootstrap-v4.6.0.css" />
  <style>
    .thumb-box {
      text-align: center;
      margin-top: 50px;
    }

    .thumb {
      width: 150px;
      height: 150px;
      object-fit: cover;
      border-radius: 50%;
    }
  </style>
</head>

<body>
  <div class="thumb-box">
    <!-- 头像 -->
    <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="" />
    <div class="mt-2">
      <!-- 文件选择框 -->
      <!-- accept 属性表示可选择的文件类型 -->
      <!-- image/* 表示只允许选择图片类型的文件 -->
      <input type="file" id="iptFile" accept="image/*" style="display: none;" />
      
      <!-- 选择头像图片的按钮 -->
      <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
    </div>
  </div>
  <script src="./lib/axios.js"></script>
  
  <script>
    document.querySelector('#btnChoose').addEventListener('click', function () {
      document.querySelector('#iptFile').click()
    })
    // 监听input框的change事件,文件每改变一次,就发一起一次请求
    document.querySelector('#iptFile').onchange = function (e) {
      const data1 = new FormData()
      data1.append('avatar', e.target.files[0])
      console.log(e.target.files[0])
      if (e.target.files[0].type.includes('image')) {
        axios({
          url: 'http://ajax-api.itheima.net/api/file',
          method: 'post',
          data: data1
        }).then((res) => {
          console.log('res',res)
          //渲染出来
          document.querySelector('.img-thumbnail').src = res.data.data.url
          console.log(document.querySelector('.img-thumbnail'))
        })
      } else {
        alert('请选择图片文件')
      }
    }
  </script>
</body>

</html>